using System;
using System.Data;
using System.Configuration;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;

using CMS.Core.DataInterfaces;
using CMS.Data;
using CMS.Core.Domain;
using CMS.Presenters.Presenters;
using CMS.Presenters.Views;

namespace CMS.Web.ListManager
{
    public partial class EditNguoiSuDung : BaseUserControl, IEditNguoiSuDungView
    {
        private EditNguoiSuDungPresenter presenter;
        private NguoiSuDung obj;
        // For Phong ban
        IList<PhongBan> pbList;
        IList<NhomNguoiSuDung> gList;
        IList<ChucNang> cnList;
        IList<VaiTro> vtList;

        int index = 0;
        String VaiTroOfSelectedGroup = "";

        public EditNguoiSuDung()
        {
            this.presenter = new EditNguoiSuDungPresenter(this, NHibernateDaoFactory.Instance.GetNguoiSuDungDao());
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            presenter.InitViewForEditing(Request.QueryString["objID"], false);
            if (!this.IsPostBack)
            {
                this.presenter.LoadViewFromModel();

                hidID.Value = this.obj.ID;
                txtName.Text = this.obj.TenNguoiSuDung;
                txtChucVu.Text = this.obj.ChucVu;
                txtTenTruyCap.Text = this.obj.TenTruyCap;
                txtMatKhau.Text = this.obj.MatKhau;
                hidPass.Value = this.obj.MatKhau;
                radStatus.SelectedIndex = (this.obj.TrangThai) ? 0 : 1;
                txtThuTu.Text = this.obj.ThuTu.ToString();               

                this.drpGroup.DataSource = this.GroupList;
                this.drpGroup.DataBind();
                ListItem item = drpGroup.Items.FindByValue(this.obj.MaNhom.ToString());
                if (item != null) item.Selected = true;

                this.chkRoles.DataSource = this.VaiTroList;
                this.chkRoles.DataBind();

                if (this.obj.NhomNguoiSuDung != null)
                {
                    this.presenter.GetFunctionsNotOfGroup(this.obj.MaNhom.ToString());
                }
                else
                {
                    if (this.GroupList.Count > 0)
                    {
                        this.presenter.GetFunctionsNotOfGroup(this.GroupList[0].ID.ToString());
                    }
                    else
                    {
                        this.presenter.GetFunctionsNotOfGroup("");
                    }
                }

                if (this.obj.NhomNguoiSuDung != null)
                {
                    this.VaiTroOfSelectedGroup = this.obj.NhomNguoiSuDung.ChucNang;
                }
                else
                {
                    if (this.GroupList.Count > 0)
                    {
                        this.VaiTroOfSelectedGroup = this.GroupList[0].ChucNang;
                    }
                }

                if (this.obj.ChucNang != "" && this.obj.ChucNang != null)
                {
                    this.VaiTro = this.obj.ChucNang;
                }
                else
                {
                    this.VaiTro = this.VaiTroOfSelectedGroup;
                    //if (this.obj.NhomNguoiSuDung != null)
                    //{
                    //    this.VaiTro = this.obj.NhomNguoiSuDung.ChucNang;
                    //}
                    //else
                    //{
                    //    if (this.GroupList.Count > 0)
                    //    {
                    //        this.VaiTro = this.GroupList[0].ChucNang;
                    //    }
                    //}
                }

                //BuildTreeRoot(trvFunctions, this.ChucNangList);
                //CheckExistRoots(trvFunctions, this.obj.ChucNangs);

                if (presenter.IsUsingLDAP)
                {
                    if (this.obj.TenTruyCap != null)
                    {
                        if (!this.obj.TenTruyCap.Equals(""))
                        {
                            this.txtTenTruyCap.Enabled = false;
                        }
                    }
                    this.txtMatKhau.Visible = false;
                }
               
            }
            this.btnOK.Attributes.Add("onclick", "return CheckInput(0);");
        }
        
        public string Message
        {
            set { //lblMessage.Text = value; 
            }
        }

        public NguoiSuDung ObjToUpdate
        {
            get
            {
                if (this.obj != null)
                {
                    this.obj.TenNguoiSuDung = txtName.Text.Trim();
                    this.obj.MaPhongBan = "9A22666B-B88E-4564-8156-979BE5410FB8";
                    this.obj.ChucVu = txtChucVu.Text.Trim();
                    this.obj.TenTruyCap = txtTenTruyCap.Text.Trim();
                    //if (presenter.IsUsingLDAP)
                    //{
                    //    try
                    //    {
                    //        if (!this.obj.TenTruyCap.Equals(""))
                    //        {
                    //            this.txtTenTruyCap.Enabled = false;
                    //        }
                    //    }
                    //    catch { }
                    //}
                    if (txtMatKhau.Text.Trim().Equals(""))
                    {
                        this.obj.MatKhau = hidPass.Value;
                    }
                    else
                    {
                        this.obj.MatKhau = txtMatKhau.Text.Trim();
                    }

                    if (drpGroup.SelectedValue != "")
                    {
                        obj.MaNhom = Convert.ToByte(drpGroup.SelectedValue);
                    }
                    obj.ChucNang = this.VaiTro;

                    String ids = "";
                    //foreach (TreeNode node in trvFunctions.Nodes)
                    //{
                    //    if (node.Checked)
                    //    {
                    //        ids += (ids == "") ? node.Value : "," + node.Value;
                    //        String temp = GetCheckedNodeIds(node);
                    //        if (temp != "")
                    //        {
                    //            ids += "," + temp;
                    //        }
                    //    }
                    //}
                    IList<ChucNang> cnList = new List<ChucNang>();
                    if (ids != "")
                    {
                        cnList = this.presenter.GetFunctions(ids);
                    }
                    obj.ChucNangs = cnList;

                    this.obj.TrangThai = Convert.ToBoolean(radStatus.SelectedValue);
                    this.obj.ThuTu = Convert.ToInt16(txtThuTu.Text);
                }
                return this.obj;
            }
            set
            {
                if (value == null) throw new ArgumentNullException("ObjToUpdate may not be null");
                this.obj = value;
            }
        }

        public IList<PhongBan> PhongBanList
        {
            get { return this.pbList; }
            set { this.pbList = value; }
        }


        public IList<NhomNguoiSuDung> GroupList
        {
            set { this.gList = value; }
            get { return this.gList; }
        }

        public IList<ChucNang> ChucNangList
        {
            set { this.cnList = value; }
            get { return this.cnList; }
        }

        public IList<VaiTro> VaiTroList
        {
            set { this.vtList = value; }
            get { return this.vtList; }
        }

        public String VaiTro
        {
            get
            {
                String ids = "";
                foreach (ListItem item in chkRoles.Items)
                {
                    if (item.Selected) ids += (ids == "") ? item.Value : "," + item.Value;
                }
                return ids;
            }
            set
            {
                foreach (ListItem item in chkRoles.Items)
                {
                    item.Selected = false;
                    item.Enabled = true;
                }
                String[] ids = value.Split(new Char[] { ',' });
                for (int i = 0; i < ids.Length; i++)
                {
                    ListItem item = chkRoles.Items.FindByValue(ids[i]);
                    if (item != null)
                    {
                        item.Selected = true;
                        String temp = "," + this.VaiTroOfSelectedGroup + ",";
                        if (temp.IndexOf("," + ids[i] + ",") >= 0) item.Enabled = false; 
                    }

                }
            }
        }

        public String MaChucNang
        {
            get
            {
                String ids = "";
                //foreach (TreeNode node in trvFunctions.Nodes)
                //{
                //    if (node.Checked)
                //    {
                //        ids += (ids == "") ? node.Value : "," + node.Value;
                //        String temp = GetCheckedNodeIds(node);
                //        if (temp != "")
                //        {
                //            ids += "," + temp;
                //        }
                //    }
                //}
                return ids;
            }
        }

        public IList<ChucNang> ChucNangs
        {
            set
            {
                //CheckExistRoots(trvFunctions, value);
            }
        }
        public string getTenPhongBan(string code)
        {
            return presenter.getPhongBan(code).TenPhongBan;
        }

        //public bool isConnectLDAP()
        //{
        //    return presenter.IsUsingLDAP;
        //}


        private void BuildTreeRoot(TreeView trv, IList<ChucNang> cnList)
        {
            trv.Nodes.Clear();
            if (cnList.Count == 0)
                return;
            foreach (ChucNang cn in cnList)
            {
                if (cn.MaCapCha == 0)
                {
                    TreeNode nodetmp = new TreeNode(cn.TenChucNang, cn.ID.ToString());
                    nodetmp.Target = cn.ID.ToString();
                    trv.Nodes.Add(nodetmp);
                    nodetmp.ShowCheckBox = true;
                    nodetmp.SelectAction = TreeNodeSelectAction.None;
                    BuildTree(nodetmp, cnList);
                    //nodetmp.Expand();
                }
            }
        }

        private void BuildTree(TreeNode node, IList<ChucNang> cnList)
        {
            if (cnList.Count == 0)
                return;
            foreach (ChucNang cn in cnList)
            {
                if (cn.MaCapCha.ToString() == node.Value)
                {
                    TreeNode nodetmp = new TreeNode(cn.TenChucNang, cn.ID.ToString());
                    nodetmp.Target = cn.ID.ToString();
                    nodetmp.ShowCheckBox = true;
                    nodetmp.SelectAction = TreeNodeSelectAction.None;
                    node.ChildNodes.Add(nodetmp);
                    BuildTree(nodetmp, cnList);
                    //nodetmp.Expand();
                }
            }
        }

        private void CheckExistRoots(TreeView trv, IList<ChucNang> cnList)
        {
            foreach (TreeNode node in trv.Nodes)
            {
                foreach (ChucNang cn in cnList)
                {
                    if (node.Value == cn.ID.ToString())
                    {
                        node.Checked = true;
                        node.SelectAction = TreeNodeSelectAction.None;
                        CheckExistNodes(node, cnList);
                    }
                }
            }
        }

        private void CheckExistNodes(TreeNode parent, IList<ChucNang> cnList)
        {
            foreach (TreeNode node in parent.ChildNodes)
            {
                foreach (ChucNang cn in cnList)
                {
                    if (node.Value == cn.ID.ToString())
                    {
                        node.Checked = true;
                        CheckExistNodes(node, cnList);
                    }
                }

            }
        }

        private String GetCheckedNodeIds(TreeNode parent)
        {
            String ids = "";
            foreach (TreeNode node in parent.ChildNodes)
            {
                if (node.Checked)
                {
                    ids += (ids == "") ? node.Value : "," + node.Value;
                    String temp = GetCheckedNodeIds(node);
                    if (temp != "")
                    {
                        ids += "," + temp;
                    }
                }
            }
            return ids;
        }


        #region Button Members
        protected void btnOK_Click(object sender, EventArgs e)
        {
            presenter.UpdateObj(Page.IsValid);
            this.btnCancel_Click(this, null);
        }

        protected void btnOKC_Click(object sender, EventArgs e)
        {
            presenter.UpdateObj(Page.IsValid);
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect(this.BaseUrl + "&action=VIEW");
        }
        #endregion

        protected void drpGroup_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.VaiTroOfSelectedGroup = this.presenter.GetRolesOfGroup(drpGroup.SelectedValue);
            this.VaiTro = this.VaiTroOfSelectedGroup;
            this.presenter.GetFunctionsNotOfGroup(drpGroup.SelectedValue);
            //BuildTreeRoot(trvFunctions, this.ChucNangList);
            //CheckExistRoots(trvFunctions, this.obj.ChucNangs);
        }
    }
}